package org.example.casLoginDemo.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    //常量
    public static final long EXPIRE = 1000 * 60 * 60 * 24;//token过期时间
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";//秘钥

    public static  String getToken(Map<String,String> map){
        String token = "";
        JwtBuilder JwtToken = Jwts.builder();
        //设置Jwt头信息
        JwtToken.setHeaderParam("typ", "JWT");
        JwtToken.setHeaderParam("alg", "HS256");
        //payload
        map.forEach((key,value)->{
            JwtToken.claim(key,value);
        });
        JwtToken.setExpiration(new Date(System.currentTimeMillis() + EXPIRE));
        JwtToken.signWith(SignatureAlgorithm.HS256,APP_SECRET);
        token = JwtToken.compact();
        return token;
    }

    //解析token
    public static Jws<Claims> verify(String token){
       return Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
    }
    
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("name","zs");
        map.put("id","1234");
        String token = getToken(map);
        System.out.println("生成token-------"+token);

        Jws<Claims> payload = verify(token);
        //payload
        Claims body = payload.getBody();
        //签名
        String signature = payload.getSignature();
        //头部信息
        payload.getHeader().get("typ");

        System.out.println("name-----"+body.get("name") + "       id--"+body.get("id") +"   signature      "+signature +"    head   " + payload.getHeader().get("typ"));



    }

}

